package com.zc.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.zc.feignservice.PaymentHystrixService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @description:
 * @author: cong
 * @create: 2024/10/14
 */
@RestController
@Slf4j
// 全局降级
//@DefaultProperties(defaultFallback = "globalFallback")
public class OrderHystrixController {
    @Autowired
    private PaymentHystrixService paymentHystrixService;

    @GetMapping("/hystrix/ok")
    public String paymentInfoOk() {
        return paymentHystrixService.paymentInfoOk();
    }

    @GetMapping("/hystrix/timeout")
//    @HystrixCommand
    @HystrixCommand(fallbackMethod = "fallback", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public String paymentTimeOut() {
        return paymentHystrixService.paymentTimeOut();
    }

    public String fallback() {
        return "时间太久了，我不等了";
    }

    //全局方法降级
    public String globalFallback(){
        return "全局降级！时间能治愈一切！";
    }

    /**
     * 断路器
     * 当10s内请求失败率达到60%，断路器开启，开启后10s内请求都失败，断路器开启，开启后请求都成功，断路器关闭
     * @return
     */
    @HystrixCommand(fallbackMethod = "circuitBreakerFallback",commandProperties ={
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), // 时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")// 失败率达到多少后跳闸
    })
    @GetMapping("/hystrix/circuit/{id}")
    public String circuitBreaker(@PathVariable("id") Integer id) {
        if (id < 0) {
            throw new RuntimeException("id不能为负数");
        }
        return paymentHystrixService.paymentInfoOk();
    }

    public String circuitBreakerFallback(Integer id) {
        return "服务熔断！";
    }
}
